<!DOCTYPE html>
{% load static %}
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>示例2：临时凭证上传文件</h1>

<input type="file" name="upload_file" id="uploadFile" multiple>
<script src="{% static 'js/jquery-3.5.1.js' %}"></script>
<script src="{% static 'plugin/cos-js-sdk-v5-master/dist/cos-js-sdk-v5.min.js' %}"></script>
<script>
    var cos;
    $(function () {
        initCOS();
        bindChangeFileInput();
    });

    // 带上凭证
    function initCOS() {
        cos = new COS({
            getAuthorization: function (options, callback) {
                // 异步获取临时密钥
                $.get('/cos/credential/', {

                }, function (data) {
                    var credentials = data && data.credentials;
                    if (!data || !credentials) return console.error('credentials invalid');
                    callback({
                        TmpSecretId: credentials.tmpSecretId,
                        TmpSecretKey: credentials.tmpSecretKey,
                        XCosSecurityToken: credentials.sessionToken,
                        StartTime: data.startTime, // 时间戳，单位秒，如：1580000000
                        ExpiredTime: data.expiredTime, // 时间戳，单位秒，如：1580000900
                    });
                });
            }
        });
    }

    function bindChangeFileInput() {
        $("#uploadFile").change(function () {
            // 获取files的属性
            var files = $(this)[0].files;
            // 可以多选来个循环(这里用each防止闭包)
            $.each(files, function(index, fileObject) {
                var fileName = fileObject.name;
                //上传文件
                cos.putObject({
                    Bucket: 'miaojiaxi-1304867879',
                    Region: 'ap-guangzhou',
                    Key: fileName, //文件名
                    StorageClass: 'STANDARD',
                    Body: fileObject, //文件对象
                    onProgress: function (progressData) {
                        console.log("文件上传进度---->", fileName, JSON.stringify(progressData));
                    }
                }, function (err, data) {
                    //打印错误信息
                    console.log(err || data);
                })
            });
        })
    }
</script>
</body>
</html>